using System;
using Gtk;
using System.Data;
using MySql.Data.MySqlClient;
using Serpis;
using PComponentes;

public partial class MainWindow : Gtk.Window
{
	private Type type;
	private IDbConnection dbConnection;
	private EditWindow editWindow;
	
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		// Definimos el tipo de conexion;
		type = typeof(MySqlConnection);
		AppDbConnection.Instance.Type = type;
		dbConnection = AppDbConnection.Instance.CreateConnection("root", "sistemas");
		if(dbConnection.State != ConnectionState.Open)
		{
			Console.WriteLine("ERROR AL CONECTAR. No se puedo establecer la conexion");
		}
		else
		{
			my_treeview.Init(dbConnection, "SELECT * FROM articulo;");
		}
		editAction.Sensitive = false;
		infoAction.Sensitive = false;
		deleteAction.Sensitive = false;
		
		my_treeview.Changed += delegate
		{
			if(my_treeview.TreeViewHelper.HasSelected == true)
			{
				editAction.Sensitive = true;
				infoAction.Sensitive = true;
				deleteAction.Sensitive = true;
				newAction.Sensitive = false;
			}
			else
			{
				editAction.Sensitive = false;
				infoAction.Sensitive = false;
				deleteAction.Sensitive = false;
				newAction.Sensitive = true;
			}
		};
		editAction.Activated += delegate 
		{
			 string id = my_treeview.GetValue(0);
			 string nombre = my_treeview.GetValue(1);
			 string precio = my_treeview.GetValue(2);
			 string categoria = my_treeview.GetValue(3);
			
			EditWindow editWindow = new EditWindow(id, nombre, precio, categoria);
			editWindow.Saved += delegate
			{
				my_treeview.Refresh();
			};
		};
		newAction.Activated += delegate 
		{
			int id = my_treeview.TreeViewHelper.NextId();
			EditWindow editWindow = new EditWindow(id.ToString(), "", "", "");
			editWindow.Saved += delegate
			{
				my_treeview.Refresh();
			};
		};
		deleteAction.Activated += delegate 
		{
			string this_id = my_treeview.GetValue(0);
			string queryDelete = "DELETE FROM articulo WHERE id='"+this_id+"';";
			my_treeview.Init(dbConnection, queryDelete);
			my_treeview.Init(dbConnection, "SELECT * FROM articulo;");
		};
		infoAction.Activated += delegate
		{
			 string id = my_treeview.GetValue(0);
			 string nombre = my_treeview.GetValue(1);
			 string precio = my_treeview.GetValue(2);
			 string categoria = my_treeview.GetValue(3);
			
			EditWindow editWindow = new EditWindow(id, nombre, precio, categoria);
			editWindow.desactivar();
		};
	}

	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
}

